import { useEffect, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import dayjs from 'dayjs'
import { Avatar, Button, Card, Flex, Input, List, message, Space, Spin, Tooltip } from 'antd'
import { DeleteOutlined, FileImageFilled, SendOutlined } from '@ant-design/icons'

import { CusImage } from '@/components/CusImage'
import { FormItemUpload, TFile } from '@/components/FormItemUpload'
import { getGlobalState } from '@/globalStore/globalStore'
import { IUserInfo } from '@/globalStore/userInfo'
import { fileValidate } from '@/utils/utils'
import { apiAddNote, apiGetNote } from '../../apis'
import { IAddNoteReq } from '../../interface'
import { useUrlParams } from '../../utils'
import styles from './styles.module.less'

export const Remarks = () => {
  const { waybillNo } = useUrlParams()
  const [commentList, setCommentList] = useState<
    {
      username: string
      userId: number
      userAvatar: string
      commentTime: string
      comment?: string
      fileUrl?: string
    }[]
  >([])
  const userInfo = getGlobalState().userInfo as IUserInfo
  const [form, setForm] = useState<{ files: TFile[]; text: string }>({ files: [], text: '' })
  const [loading, setLoading] = useState(false)
  const [sendLoading, setSendLoading] = useState(false)

  /** 发送备注 */
  const handleSend = useMemoizedFn(async () => {
    try {
      if (waybillNo) {
        setSendLoading(true)
        const req: IAddNoteReq = {
          waybillNo,
          note: form.text,
          fileUrl: form.files[0]?.fileUrl,
        }
        await apiAddNote(req)
        message.success('发送成功')
        setForm({ text: '', files: [] })
      }

      setCommentList([
        ...(commentList || []),
        {
          username: userInfo?.username ?? '',
          userId: userInfo?.id ?? 0,
          userAvatar: userInfo?.avatar ?? '',
          commentTime: dayjs().format('MM-DD HH:mm'),
          comment: form.text,
          fileUrl: form.files[0]?.fileUrl,
        },
      ])
    } finally {
      setSendLoading(false)
    }
  })

  const getCommentList = useMemoizedFn(async () => {
    try {
      if (waybillNo) {
        setLoading(true)
        const res = await apiGetNote({ waybillNo })
        setCommentList(
          (res || []).map(item => ({
            username: item.user?.username ?? '',
            userId: item.user?.id ?? 0,
            userAvatar: item.user?.avatar ?? '',
            commentTime: item.createAt ? dayjs(item.createAt).format('MM-DD HH:mm') : '',
            comment: item.note ?? '',
            fileUrl: item.fileUrl ?? '',
          })),
        )
      }
    } finally {
      setLoading(false)
    }
  })

  useEffect(() => {
    getCommentList()
  }, [])

  return (
    <Card title="备注信息">
      <div className={styles.main}>
        <div className={styles.main_container}>
          <List
            itemLayout="horizontal"
            dataSource={commentList || []}
            locale={{
              emptyText: '暂无留言记录',
            }}
            renderItem={item => (
              <List.Item>
                <List.Item.Meta
                  avatar={<Avatar src={item?.userAvatar} />}
                  title={
                    <Space>
                      {item.username}
                      {item?.commentTime && <div style={{ color: 'rgba(0,0,0,0.45)' }}>{item?.commentTime}</div>}
                    </Space>
                  }
                  description={
                    <div>
                      <div dangerouslySetInnerHTML={{ __html: (item.comment ?? '')?.replace(/\n/g, '<br/>') }} />
                      <div>{item?.fileUrl && <CusImage width={50} height={50} src={item.fileUrl || ''} />}</div>
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        </div>

        {waybillNo && (
          <div className={styles.main_footer}>
            <div className={styles.main_footer_input}>
              <Flex align="center" gap={8}>
                <Input.TextArea
                  placeholder="请输入你的留言..."
                  value={form.text}
                  autoSize={{ minRows: 1, maxRows: 2 }}
                  onChange={e => setForm(prev => ({ ...prev, text: e.target.value }))}
                  onKeyDown={e => {
                    if (e.ctrlKey && e.key === 'Enter') {
                      handleSend()
                    }
                  }}
                />
                <FormItemUpload
                  listType="text"
                  maxCount={1}
                  value={form.files}
                  accept={fileValidate.IMG_ACCEPT}
                  reqData={{ moduleType: 1 }}
                  itemRender={undefined}
                  showUploadList={false}
                  onChange={list => {
                    setForm(prev => ({ ...prev, files: list }))
                  }}
                  onRowChange={val => {
                    if (val?.length > 0) {
                      setLoading(false)
                    } else {
                      setLoading(true)
                    }
                  }}
                >
                  <Spin spinning={loading}>
                    <Button variant="link" color="default" icon={<FileImageFilled />}></Button>
                  </Spin>
                </FormItemUpload>
                <Tooltip title="发送 (Ctrl+Enter)">
                  <Button
                    type="primary"
                    disabled={!(form.text || form.files?.length > 0)}
                    size="small"
                    loading={sendLoading}
                    icon={<SendOutlined />}
                    style={{ width: 44 }}
                    className={styles.sendButton}
                    onClick={handleSend}
                  />
                </Tooltip>
              </Flex>
            </div>
            {form.files?.length > 0 && (
              <div className={styles.main_footer_imgs}>
                {form.files?.map((file, index) => {
                  return (
                    <div key={index} className={styles.main_footer_imgs_item}>
                      <div>
                        <CusImage width={50} height={50} src={file?.fileUrl} />
                      </div>
                      {file?.fileUrl && (
                        <Tooltip title="删除">
                          <Button
                            type="link"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={() => setForm(prev => ({ ...prev, files: [] }))}
                          />
                        </Tooltip>
                      )}
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        )}
      </div>
    </Card>
  )
}
